package com.softserve.academy.food.dao;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;

import org.springframework.stereotype.Repository;

import com.softserve.academy.food.entity.eUser;

import java.util.ArrayList;
import java.util.List;

@Repository
public class HibernateUser extends Dao
{
	public ArrayList<eUser> Create(ArrayList<?> list) 
	{
		ArrayList<eUser> save = new ArrayList<eUser>();

		for (Object obj  : list)
		{
			eUser eUser = (eUser)obj;
			eUser.setId( (Integer)sessionFactory.getCurrentSession().save( obj ));
			save.add(eUser);
		}	
		return save;
	}
	
	public eUser Create(eUser user) 
	{
		if (user!=null)
		{
			user.setId( (Integer)sessionFactory.getCurrentSession().save( user ));
		}	
		return user;
	}
	
	public void Delete(int id)  
	{
		Query query;
		query = sessionFactory.getCurrentSession().createQuery("delete from eUser where User_ID = " + id);
		query.executeUpdate();
	}

	public void DeleteAll()  
	{
		Query query;
		query = sessionFactory.getCurrentSession().createQuery("delete from eUser");
		query.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public eUser Read(eUser user)  
	{
		int id = user.getId();
		
		List<eUser> list = sessionFactory.getCurrentSession().createQuery( "from eUser where User_ID = "+id ).list();
		
		if (list.isEmpty())
		{
			return user;
		}
		
		return list.get(0);
	}
	
	@SuppressWarnings("unchecked")
	public eUser Read(int id)  
	{
		eUser user = new eUser();
		
		List<eUser> list = sessionFactory.getCurrentSession().createQuery("from eUser where User_ID = "+id).list();
		
		if ( list.isEmpty() )
		{
			return user;
		}
		
		return list.get(0);
	}

	@SuppressWarnings("unchecked")
	public ArrayList<eUser> ReadAll()  
	{
		return (ArrayList<eUser>) sessionFactory.getCurrentSession().createQuery("from eUser").list();
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<eUser> findUser(String login)
	{
		ArrayList<eUser> findlist = new ArrayList<eUser>();
		
		Criteria crit = sessionFactory.getCurrentSession().createCriteria(eUser.class);
		crit.add(Restrictions.ilike("login", "%"+login+"%"));

		findlist = (ArrayList<eUser>) crit.list();
		
		return findlist;
	}
	
	@SuppressWarnings("unchecked")
	public eUser getUser( String login )
	{
		List<eUser> list = sessionFactory.getCurrentSession().createQuery("from eUser where USERNAME = '"+login+"'").list();
		
		if ( list.isEmpty() )
		{
			return new eUser();
		}
		return list.get(0);
	}

}
